#coding:utf-8
import colorsys
from PIL import Image
import urllib
import requests
from io import BytesIO
from flask_restful import Api, Resource

def get_dominant_color(image):
#颜色模式转换，以便输出rgb颜色值
    image = image.convert('RGBA')
#生成缩略图，减少计算量，减小cpu压力
    image.thumbnail((200, 200))
    max_score = 0 #原来的代码此处为None
    dominant_color = 0  #原来的代码此处为None，但运行出错，改为0以后 运行成功，原因在于在下面的 score > max_score的比较中，max_score的初始格式不定
    for count, (r, g, b, a) in image.getcolors(image.size[0] * image.size[1]):
        # 跳过纯黑色
        if a == 0:
            continue
        saturation = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)[1]
        y = min(abs(r * 2104 + g * 4130 + b * 802 + 4096 + 131072) >> 13, 235)
        y = (y - 16.0) / (235 - 16)
        # 忽略高亮色
        if y > 0.9:
            continue
        # Calculate the score, preferring highly saturated colors.
        # Add 0.1 to the saturation so we don't completely ignore grayscale
        # colors by multiplying the count by zero, but still give them a low
        # weight.
        score = (saturation + 0.1) * count
        if score > max_score:
            max_score = score
            dominant_color = (r, g, b)
    
    return dominant_color

def readUrl():
    r = urllib.request.urlopen('http://media.dailyupward.com/000e38fa0f1563374838140')
    f = open('temp.jpg','wb')
    f.write(r.read())
    f.close()
    img = Image.open('./temp.jpg')  # PIL库加载图片
    tp_color = get_dominant_color(img)
    str_color = "%d,%d,%d" % (tp_color[0], tp_color[1], tp_color[2])
    print(str_color)
    return str_color

def readUrlByByteIO():
    res = requests.get('http://media.dailyupward.com/000e38fa0f1563374838140',stream=True)
    byte_stream = BytesIO()
    byte_stream.write(res.content)
    byte_stream.seek(0)
    img = Image.open(byte_stream)
    #img.show()
    return get_dominant_color(img)

def readUrlByRequest():
    r = urllib.request.urlopen('http://media.dailyupward.com/000e38fa0f1563374838140')
    imgBuf = BytesIO(r.read())
    img = Image.open(imgBuf)
    #img.show()
    return get_dominant_color(img)

class DominantColor(Resource):
    def get(self):
        #return readUrlByByteIO()
        #return readUrlByRequest()
        return readUrl()
 
if __name__ == '__main__':
    readUrl()